import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-10-24
 * Time: 12:05
 */
@WebServlet("/showhttp")
public class ShowRequestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuffer stringBuffer = new StringBuffer();
        //调用Httprequest中的常用方法, 获取 http报文中的信息,将调用结果显示页面上
        stringBuffer.append(req.getProtocol());    //获取协议名称并在页面上显示
        stringBuffer.append("<br>");

        stringBuffer.append(req.getRequestURI());    //获取协议URL的一部分
        stringBuffer.append("<br>");

        stringBuffer.append(req.getContextPath());    //获取 返回指示请求的URI部分
        stringBuffer.append("<br>");

        stringBuffer.append(req.getQueryString());    //获取Url中的 查询语句
        stringBuffer.append("<br>");

        Enumeration<String> headerNames = req.getHeaderNames();    //获取 Header中所有的 key;
        while(headerNames.hasMoreElements()) {   //遍历 枚举的集合,获得每一个key的名字
            String name = headerNames.nextElement();
            stringBuffer.append(name + ": " + req.getHeader(name)); //通过key的name 在请求中找到对应的value
            stringBuffer.append("<br>");
        }
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(stringBuffer.toString());
    }
}
